package com.ruoyi.framework.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.exception.user.UserNullException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 微信注册方法
 */
@Component
public class SysRegisterService {
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 注册用户绑定微信oppenId
     * @param registerBody
     * @return
     */
    public AjaxResult register(RegisterBody registerBody){

        String verifyKey = Constants.CAPTCHA_CODE_KEY +registerBody.getWechatId() ;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!registerBody.getCode().equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }

        SysUser user=iSysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName,registerBody.getUserName())
                .eq(SysUser::getNickName,registerBody.getNickName()));

        if (user==null){
            throw new CustomException("用户不存在",303);
//            return new AjaxResult().success("用户不存在");
        }

        user.setWechatId(registerBody.getWechatId());
        boolean tf=iSysUserService.saveOrUpdate(user);

        if (tf){

            return new AjaxResult().success("注册成功");
        }
        throw new CustomException("注册失败",303);
    }
}
